import java.util.*;
public class Solution {
    public class ListNode {
        int val;
        ListNode next = null;

        public ListNode(int val) {
            this.val = val;
        }
    }
    public ListNode func(ListNode l) {
        ListNode cur = l;
        ListNode prev = null;
        while (cur != null) {
            ListNode next = cur.next;
            next.next = cur;
            cur = next;
        }
        return prev;
    }

    public ListNode addInList(ListNode head1, ListNode head2) {
        // write code here
        ListNode l1 = func(head1);
        ListNode l2 = func(head2);
        ListNode ret = new ListNode(-1);
        int sum = 0;
        ListNode cur = ret;
        while (l2 != null && l1 != null) {
            sum += l2.val + l1.val;
            cur.next = new ListNode(sum % 10);
            cur = cur.next;
            sum /= 10;
            l2 = l2.next;
            l1 = l1.next;
        }
        while (l2 != null) {
            sum += l2.val;
            cur.next = new ListNode(sum % 10);
            cur = cur.next;
            sum /= 10;
            l2 = l2.next;
        }
        while (l1 != null) {
            sum += l1.val;
            cur.next = new ListNode(sum % 10);
            cur = cur.next;
            sum /= 10;
            l1 = l1.next;
        }
        if (sum != 0) cur.next = new ListNode(sum);
        return func(ret.next);
    }
}